package com.paishen.peiniwan.frame;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.paishen.common.okhttp.OkCallbackAdapter;
import com.paishen.common.util.LogUtil;
import com.paishen.common.util.NetworkUtil;
import com.paishen.peiniwan.ActivityCollector;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.module.login.AmazingLRActivity;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

/**
 * 使用通用的失败回调逻辑，如果不使用则重写onFailure
 *
 * @param <T>
 */
public class PnwOkCallbackAdapter<T extends HttpResp> extends OkCallbackAdapter<T> {

    private boolean useCache;
    private String key;
    private String t;

    public PnwOkCallbackAdapter setCache(String tag, String url, Map<String, String> params) {
        useCache = true;
        key = url + "#" + params;
        t = tag;
        return this;
    }

    public static class Cache {
        public String tag;
        public String key;
        public byte[] content;

        Cache(String tag, String key, byte[] content) {
            this.tag = tag;
            this.key = key;
            this.content = content;
        }
    }

    @Override
    public void onResponse(final T response, boolean fresh) {
        super.onResponse(response, fresh);

        if (fresh && (response.errcode == C.http.RESULT_LOGIN_EXPIRE ||
                response.errcode == C.http.RESULT_LOGIN_OFFLINE)) {
            EMClient.getInstance().logout(true, new EMCallBack() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });

            // 清空登录信息
            MobclickAgent.onProfileSignOff();
            JPushInterface.stopPush(App.i());
            com.paishen.peiniwan.database.User loginUser = App.i().getUser();
            loginUser.setApp_auto_login(false);
            EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, loginUser));

            final BaseActivity top = (BaseActivity) ActivityCollector.getTop();
            if (top.dlgLoginInfo == null) {
                top.dlgLoginInfo = new AlertDialog.Builder(top).setTitle(R.string.error_offline).setMessage(response.errmsg)
                        .setCancelable(false).setPositiveButton(R.string.login_again
                                , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                top.dlgLoginInfo.dismiss();
                                Intent intent = new Intent(top, AmazingLRActivity.class);
                                intent.putExtra(AmazingLRActivity.EXTRA_MODE_LOGIN, true);
                                top.startActivity(intent);
                                ActivityCollector.finishAllExcept(AmazingLRActivity.class);
                            }
                        }).setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                top.dlgLoginInfo.dismiss();
                                ActivityCollector.finishAll();
                            }
                        }).create();
            }
            top.dlgLoginInfo.show();
            return;
        }

        if (useCache && fresh) {
            EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_HTTP_CACHE, new Cache(t, key, App.i().getGson().toJson(response).getBytes())));
        }
    }

    @Override
    public void onFailure(Request request, Exception e) {
        super.onFailure(request, e);
        Toast.makeText(App.i(), NetworkUtil.isNoInternet() ? R.string.error_net : R.string.error_request, Toast.LENGTH_SHORT).show();

        LogUtil.e("PnwOkCallbackAdapter onFailure\n" + key);
        takeOutCache();
    }

    public void takeOutCache() {
        if (useCache) {
            LogUtil.d("PnwOkCallbackAdapter takeOutCache\n" + key);
            InputStream mCacheSteam = App.i().getHttpCacheUtil().read(key);
            if (mCacheSteam != null) {
                Gson gson = App.i().getGson();
                onResponse((T) gson.fromJson(new InputStreamReader(mCacheSteam), mType), false);
            }
        }
    }
}
